/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package util;

import clases.ClsContraladorEventos;
import clases.ClsMetodos;
import java.awt.Point;
import java.awt.Rectangle;
import java.awt.event.KeyEvent;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JViewport;
import javax.swing.ListSelectionModel;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;


/**
 *
 * @author Miguel
 */
public class Prueba1Table {

    static ClsContraladorEventos contraladorEventos=new ClsContraladorEventos();

    static int[] caracterAscii={
        34,// " comillas
        35,// # simbolo michi
        36,// $ simbolo de dolar
        37,// % porcentaje
        38,// & ampersand
        39,// ' apostrofe
        40,// ( parentesis de apertura
        41,// ) parentesis de cierre
        42,// * asterisco
        43,// + simbolo de suma
        44,// , coma
        45,// - guion
        46,// . punto
        47,// / splash
        58,// :
        59,// ;
        167// °
    };
    /**
     * @param args the command line arguments
     */
    public static void main(String[] args){
        //Para el metodo de Redondeo
        System.out.println("2deciamles-->"+String.valueOf(ClsMetodos.Redondear(234.123434315345, 2)));
        System.out.println("3deciamles-->"+String.valueOf(ClsMetodos.Redondear(234.123434315345, 3)));
        System.out.println("4deciamles-->"+String.valueOf(ClsMetodos.Redondear(234.123434315345, 4)));
        System.out.println("5deciamles-->"+ClsMetodos.Redondear_String(234.123434315345, 5));
        System.out.println("6deciamles-->"+ClsMetodos.Redondear_String(234.123434315345, 6));
        System.out.println("7deciamles-->"+ClsMetodos.Redondear_String(234.123434315345, 7));

        String Str = "Wel.come to .Tutorialspoint.com";
      String SubStr1 = ".";
      String SubStr2 = "co";

      System.out.print("Found Last Index :" );
      System.out.println(Str.lastIndexOf( 'o' ));
      System.out.print("Found Last Index :" );
      System.out.println(Str.lastIndexOf( 'o', 5 ));
      System.out.print("Found Last Index "+SubStr1+":" );
      System.out.println( Str.lastIndexOf( SubStr1 ));
      System.out.print("Found Last Index "+SubStr1+":" );
      System.out.println( Str.lastIndexOf( SubStr1, 15 ));
      System.out.print("Found Last Index "+SubStr1+":" );
      System.out.println(Str.lastIndexOf( SubStr1 ));

        JFrame frame = new JFrame();
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setLocationRelativeTo(null);
    final JTable table;

    String[] columnTitles = { "A", "B", "C", "D" };
    Object[][] rowData = { { "11", "12", "13", "14" }, { "21", "22", "23", "24" },
        { "31", "32", "33", "34" }, { "41", "42", "44", "44" } };

    table = new JTable(rowData, columnTitles);

    table.setCellSelectionEnabled(true);
    ListSelectionModel cellSelectionModel = table.getSelectionModel();
    cellSelectionModel.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);

    cellSelectionModel.addListSelectionListener(new ListSelectionListener() {
      public void valueChanged(ListSelectionEvent e) {
        String selectedData = null;

        int[] selectedRow = table.getSelectedRows();
        int[] selectedColumns = table.getSelectedColumns();

          System.out.println("selectedRow: "+selectedRow.length);
          System.out.println("selectedColums: "+selectedColumns.length);
          
        for (int i = 0; i < selectedRow.length; i++) {
          for (int j = 0; j < selectedColumns.length; j++) {
            selectedData = (String) table.getValueAt(selectedRow[i], selectedColumns[j]);
          }
        }
        System.out.println("Selected: " + selectedData);
      }

    });
//___________________________________________________________________________________ Soy una barra separadora :)
    table.addMouseListener(new MouseListener() {

            @Override
            public void mouseClicked(MouseEvent evt) {
                if (evt.getClickCount() == 2) {
                    int fila = table.getSelectedRow();
                    int columna = table.getSelectedColumn();
                    
                }
            }

            @Override
            public void mousePressed(MouseEvent e) {
//                throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
            }

            @Override
            public void mouseReleased(MouseEvent e) {
//                throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
            }

            @Override
            public void mouseEntered(MouseEvent e) {
//                throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
            }

            @Override
            public void mouseExited(MouseEvent e) {
//                throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
            }
        });
//___________________________________________________________________________________ Soy una barra separadora :)
//    scrollToVisible(table, 2, 2);
    
//    int gapWidth = 10;
//    int gapHeight = 3;
//    table.setIntercellSpacing(new Dimension(gapWidth, gapHeight));
    
    SelectionListener listener = new SelectionListener(table);
    table.getSelectionModel().addListSelectionListener(listener);
    table.getColumnModel().getSelectionModel().addListSelectionListener(listener);
//______________________________________________________________:)Soy una Bara Espaciadora
//    table.setColumnSelectionAllowed(true);
//    table.setRowSelectionAllowed(true);
    //Para seleccionar una celda especifica
//    int row = 1;
//    int col = 2;
//    boolean success = table.editCellAt(row, col);
//        System.out.println("Success:"+success);
//    if (success) {
//      boolean toggle = false;
//      boolean extend = false;
//      table.changeSelection(row, col, toggle, extend);
//    }
    //______________________________________________________________:)Soy una Bara Espaciadora
//     table.addMouseListener(new java.awt.event.MouseAdapter(){
//        public void mouseClicked(java.awt.event.MouseEvent e){
//                int row=table.rowAtPoint(e.getPoint());
//                int col= table.columnAtPoint(e.getPoint());
////                JOptionPane.showMessageDialog(null," Value in the cell clicked :"+ " " +table.getValueAt(row,col).toString());
//                System.out.println("Value in the cell clicked :"+ " " +table.getValueAt(row,col).toString());
////                table.setValueAt("", row, col);
//            }
//        }
//     );
     //______________________________________________________________:)Soy una Bara Espaciadora
     table.addKeyListener(new java.awt.event.KeyListener() {
            @Override
            public void keyTyped(KeyEvent e) {
                System.out.println("KeyTyped()");
//                int row=table.rowAtPoint(e.getPoint());
//                int col= table.columnAtPoint(e.getPoint());
                
//                JOptionPane.showMessageDialog(null, "Hola");
            }

            @Override
            public void keyPressed(KeyEvent e) {
                System.out.println("KeyPressed()");
                int row=table.getSelectedRow();
                int col=table.getSelectedColumn();

                //Obtenemos el  valor de la celda
                String celdaValor=table.getValueAt(row, col).toString();
                //Si se presiona una tecla de edición, resetear la celda a ""
                if (contraladorEventos.letrasNumeros_OtrosCaracteres_v2Table(e)) {
                    table.setValueAt("", row, col);
                }
                
            }

            @Override
            public void keyReleased(KeyEvent e) {
                System.out.println("KeyReleased()");
            }
        });
    
    //______________________________________________________________:)Soy una Bara Espaciadora
    frame.add(new JScrollPane(table));

    frame.setSize(300, 200);
    frame.setVisible(true);
    }
    
    public static void scrollToVisible(JTable table, int rowIndex, int vColIndex) {
        if (!(table.getParent() instanceof JViewport)) {
          return;
        }
        JViewport viewport = (JViewport) table.getParent();
        Rectangle rect = table.getCellRect(rowIndex, vColIndex, true);
        Point pt = viewport.getViewPosition();
        rect.setLocation(rect.x - pt.x, rect.y - pt.y);
        viewport.scrollRectToVisible(rect);
  }

//    public void letrasNumeros_OtrosCaracteres_v2Table(KeyEvent e) {
//        char c = e.getKeyChar();
//        boolean value=false;
//        if ((c > 47) && (c <58)) {//Es un Numero
//            value=true;
//        }else if ((c >= 65 || c <= 90) || (c >= 97 || c <= 122)) {//Es una Letra
////            e.consume();
//            value=true;
//        }else{// Es un caracter definido en "caracterAscii[]"
//            for (int i = 0; i < caracterAscii_v2.length; i++) {
//                if (c==caracterAscii_v2[i]) {
//                    value=true;
//                    break;
//                }
//            }
//        }
//        if (value==false) {
//            e.consume();
//        }
////        return value;
//    }
}

//___________________________________________________________________________________ Soy una barra separadora :)
class SelectionListener implements ListSelectionListener {
  JTable table;

  SelectionListener(JTable table) {
    this.table = table;
  }
  @Override
  public void valueChanged(ListSelectionEvent e) {
      System.err.println("MIKE");
    if (e.getSource() == table.getSelectionModel() && table.getRowSelectionAllowed()) {
      int first = e.getFirstIndex();
      int last = e.getLastIndex();
    } else if (e.getSource() == table.getColumnModel().getSelectionModel()
        && table.getColumnSelectionAllowed()) {
      int first = e.getFirstIndex();
      int last = e.getLastIndex();
    }
    if (e.getValueIsAdjusting()) {
      System.out.println("The mouse button has not yet been released");
    }
  }
}
